import { formatRefTypeName, convertToTypeScript } from "../utils/data";
import { injectStyles } from "../utils/inject";
import { pageStyles } from "../utils/const";
import { injectScript } from "wxt/utils/inject-script";
import { observeDom } from "../utils/observer";

const BTN_TEXT = "TS 📋 ";

async function copyTsInterface(typeDefinition: any, interfaceName: string) {
  // 创建提示框
  const toast = document.createElement("div");
  toast.className = "toast-container";
  toast.innerHTML = `
      <div class="toast-header">
        <div class="toast-title">✅ 复制成功！已复制 ${interfaceName} 的类型定义</div>
        <button class="toast-close-btn">×</button>
      </div>
      <div class="toast-content">${typeDefinition}</div>
    `;
  document.body.appendChild(toast);

  // 添加关闭按钮事件
  const closeBtn = toast.querySelector(".toast-close-btn");
  closeBtn?.addEventListener("click", () => {
    toast.style.opacity = "0";
    setTimeout(() => document.body.removeChild(toast), 300);
  });

  // 尝试复制到剪贴板
  const typeDefinitionStr = (
    document.querySelector(".toast-content") as HTMLElement
  )?.innerText;
  try {
    // 优先使用现代API
    if (navigator.clipboard && navigator.clipboard.writeText) {
      await navigator.clipboard.writeText(typeDefinitionStr);
    } else {
      // 回退到传统方法
      const textArea = document.createElement("textarea");
      textArea.value = typeDefinitionStr;
      textArea.style.position = "fixed";
      textArea.style.left = "-999999px";
      textArea.style.top = "-999999px";
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      document.execCommand("copy");
      document.body.removeChild(textArea);
    }
  } catch (err) {
    console.error("复制失败:", err);
  }
}

function injectCopyTsBtn(definitions: any) {
  // 查找所有描述文本元素
  const modelTitleEls = document.querySelectorAll(".model-title__text");

  modelTitleEls.forEach((el) => {
    // 检查是否已经添加过按钮
    if (el.querySelector(".copy-description-btn")) {
      return;
    }
    const button = document.createElement("button");
    button.className = "copy-description-btn";
    button.textContent = BTN_TEXT;
    button.onclick = (e) => {
      e.stopPropagation();
      const text = el?.textContent?.replace(BTN_TEXT, "").trim() || "";
      const properties = definitions[text].properties;
      const interfaceName = formatRefTypeName(text);
      const typeDefinition = convertToTypeScript(
        properties,
        interfaceName,
        definitions
      );
      copyTsInterface(typeDefinition, interfaceName);
    };

    el.appendChild(button);
  });
}

export default defineContentScript({
  matches: ["*://*/**/swagger/**"],
  main() {
    // 检查是否为swagger页面
    if (!document.querySelector("#swagger-ui")) {
      return;
    }
    console.log(
      "%c加载swagger2Ts插件！",
      "color: #2196F3; font-size: 14px; font-weight: bold; text-shadow: 1px 1px 1px rgba(0,0,0,.2); padding: 3px;"
    );

    // 创建一个外部脚本文件的内容
    injectScript("/fetchInterceptor.js");
    // 注入一些样式
    injectStyles(pageStyles);

    // 监听fetch事件
    document.addEventListener("fetch-event", (event: any) => {
      const { type, data } = event.detail;
      if (type === "response") {
        // 监听DOM变化，为新增的描述元素添加按钮
        observeDom(document.body, () =>
          injectCopyTsBtn(data.response.definitions)
        );
      }
    });
  },
});

// 定义 Swagger 属性的接口
interface SwaggerProperty {
  type?: string;
  description?: string;
  items?: {
    type?: string;
    $ref?: string;
  };
  properties?: Record<string, SwaggerProperty>;
  $ref?: string;
}
